package com.dup.jxlh.admin.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.dup.jxlh.admin.entities.aliyun.AliYunOssToken;
import com.dup.jxlh.admin.service.AliYunOssService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service("aliYunOssServiceImpl")
public class AliYunOssServiceImpl implements AliYunOssService {
    private final String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private final String bucket = "imguploadtest002";
    private final String accessKeyId = "LTAI4G63p5VSwfSmktw8iPaP";
    private final String accessKeySecret = "nLLJcEbirNln6gbWuRPQtvxkkP3JWu";
    private final String roleArn = "acs:ram::1703124206424168:role/uploadststest";
    private final String roleSessionName = "ali-oss-test";

    @Override
    public AliYunOssToken getAliYunOssStsToken() {
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", "", "Sts", "sts.aliyuncs.com");
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(null); // 若policy为空，则用户将获得该角色下所有权限
            request.setDurationSeconds(1000L); // 设置凭证有效时间
            final AssumeRoleResponse response = client.getAcsResponse(request);

            AliYunOssToken aliYunOssToken = new AliYunOssToken();
            aliYunOssToken.setEndpoint(endpoint);
            aliYunOssToken.setBucket(bucket);
            aliYunOssToken.setCredentials(response.getCredentials());
            return aliYunOssToken;
        } catch (ClientException e) {
            System.out.println("Failed：");
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
        }
        return null;
    }

    @Override
    @Async
    public Boolean delAliYunOssFile(String url) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 删除文件
        ossClient.deleteObject(bucket, getAliYunOssFileName(url));
        // 关闭OSSClient
        ossClient.shutdown();
        return true;
    }

    private String getAliYunOssFileName(String url){
        String uri = bucket + "." + endpoint;
        Integer index = url.indexOf(uri);
        Integer len = uri.length();
        return url.substring(index + len+ 1);
    }


}
